<template>
  <div class="container">
    <Breadcrumb :items="['menu.menu']" />
    <a-card class="general-card" :title="$t('menu.menu')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 7 }"
            :wrapper-col-props="{ span: 16 }"
            label-align="left"
            size="mini"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="title" :label="`菜单标题`">
                  <a-input
                    v-model="formModel.title"
                    :placeholder="`请输入菜单标题`"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="path" :label="`菜单路径`">
                  <a-input
                    v-model="formModel.path"
                    :placeholder="`请输入菜单路径`"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="name" :label="`菜单名称`">
                  <a-input
                    v-model="formModel.name"
                    :placeholder="`请输入菜单名称`"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space :size="18">
            <a-button type="primary" @click="search" size="small">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset" size="small">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="store.add">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
            <a-button
              type="primary"
              status="danger"
              @click="store.dels(fetchData)"
            >
              <template #icon>
                <icon-Delete />
              </template>
              批量删除
            </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('searchTable.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="false"
        :size="size"
        page-position="bottom"
        @page-change="onPageChange"
        v-model:selectedKeys="store.selectedKeys"
        :row-selection="store.rowSelection"
        stripe
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <!-- <template #operations>
          <a-button v-permission="['admin']" type="text" size="small">
            {{ $t('searchTable.columns.operations.view') }}
          </a-button>
        </template> -->
        <template #status="{ record }">
          <span v-if="record.status" class="circle"></span>
          <span v-else class="circle pass"></span>
          {{ [`关闭`, `开启`][record.status] }}
        </template>
        <template #id="{ record }">
          <a-space :size="18">
            <a-button type="outline" size="small" @click="store.edit(record)">
              <template #icon>
                <icon-Edit />
              </template>
              编辑
            </a-button>

            <a-popconfirm
              content="是否确认删除?"
              type="error"
              @ok="store.del(record.id)"
            >
              <a-button type="outline" size="small" status="danger">
                <template #icon>
                  <icon-Delete />
                </template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
      <a-modal
        v-model:visible="store.status"
        :title="`${store.form?.id ? '编辑菜单' : '新建菜单'}`"
        draggable
        unmount-on-close
        @before-ok="store.handleBeforeOk"
        @close="$refs.formRef.resetFields()"
        @open="store.open(focusRef, formRef)"
      >
        <a-form ref="formRef" :model="store.form" :rules="store.rules">
          <a-form-item field="title" label="菜单标题">
            <a-input
              ref="focusRef"
              v-model="store.form.title"
              placeholder="请输入菜单标题"
            />
          </a-form-item>
          <a-form-item field="pid" label="菜单父级">
            <a-tree-select
              v-model="store.form.pid"
              :data="store.options.parr"
              placeholder="请选择菜单父级"
              allow-search
              allow-clear
              field-names="title"
              style="width: 300px"
            ></a-tree-select>
          </a-form-item>
          <a-form-item field="icon" label="菜单图标">
            <SelectIcon v-model="store.form.icon" />
          </a-form-item>
          <a-form-item field="path" label="菜单路径">
            <a-input v-model="store.form.path" placeholder="请输入菜单路径" />
          </a-form-item>
          <a-form-item field="name" label="菜单名称">
            <a-input v-model="store.form.name" placeholder="请输入菜单名称" />
          </a-form-item>
          <a-form-item field="status" label="菜单状态">
            <a-switch
              v-model="store.form.status"
              checked-text="开启"
              unchecked-text="关闭"
              :checked-value="1"
              :unchecked-value="0"
            />
          </a-form-item>

          <a-form-item field="sort" label="排序">
            <a-input-number
              v-model="store.form.sort"
              placeholder="请输入排序"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick, onMounted } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';
  import { Divider, Message, Modal } from '@arco-design/web-vue';
  import { getData, Record, Params, savetData, delData } from './api';
  import { useMenuStore } from '@/store/index';
  import SelectIcon from './components/select-icon.vue';
  const store = useMenuStore();
  console.log(store);
  const formRef = ref();
  const focusRef = ref();

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      title: ``,
      path: ``,
      name: ``,
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref([]);
  const formModel = ref(generateFormModel());
  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const size = ref<SizeProps>('small');

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
  };
  const pagination = reactive({
    ...basePagination,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    size: 'mini',
  });
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('searchTable.columns.index'),
      dataIndex: 'index',
      slotName: 'index',
      align: 'center',
      width: 60,
    },
    {
      title: `菜单标题`,
      dataIndex: 'title',
      align: 'center',
      width: 150,
    },
    {
      title: `父级`,
      dataIndex: 'p_title',
      align: 'center',
      width: 120,
    },
    {
      title: `菜单路径`,
      dataIndex: 'path',
      align: 'center',
      width: 120,
    },
    {
      title: `菜单名称`,
      dataIndex: 'name',
      align: 'center',
      width: 120,
    },
    {
      title: `菜单状态`,
      dataIndex: 'status',
      slotName: 'status',
      align: 'center',
      width: 100,
    },
    {
      title: `创建时间`,
      dataIndex: 'createtime',
      align: 'center',
      width: 180,
    },
    {
      title: `更新时间`,
      dataIndex: 'updatetime',
      align: 'center',
      width: 180,
    },
    {
      title: `操作`,
      dataIndex: 'id',
      slotName: 'id',
      align: 'center',
      fixed: 'right',
      width: 200,
    },
  ]);

  const fetchData = async (params = { current: 1, pageSize: 10 }) => {
    setLoading(true);
    try {
      const { data } = await getData(params);
      console.log(data);
      store.options.parr = data.parr;
      renderData.value = data.list;
      pagination.current = params.current;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  store.fetchData = fetchData;

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown);
  };
  const onPageChange = (current: number) => {
    fetchData({ ...basePagination, current });
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'GoodsType',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
